package com.quwan.component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.aliyuncs.exceptions.ServerException;

/**
 * @author quan
 * @date 2021-06-07 17:01
 */
//@Component
public class AliComponent {
    private static final Logger log = LoggerFactory.getLogger(AliComponent.class);
    //@Value("${sms.accessKeyId}")
    private String smsAccessKeyId;
    //@Value("${sms.accessSecret}")
    private String smsAccessSecret;
    //@Value("${sms.signName}")
    private String smsSignName;
    //@Value("${sms.templateCode}")
    private String smsTemplateCode;

    public boolean sendSms(String phoneNumbers,String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsAccessKeyId, smsAccessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", smsSignName);
        request.putQueryParameter("TemplateCode", smsTemplateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject result = JSONObject.parseObject(response.getData().toLowerCase());
            if (!result.get("code").equals("ok")){
                log.error("send msm err::{}",result.toString());
                return false;
            }
            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
